package com.bulletelc.apollopre.module.user.FastRegister;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.framework.MVPBaseFragment;
import com.bulletelc.apollopre.module.main.MainActivity;
import com.bulletelc.apollopre.module.user.LoginMainActivity;
import com.bulletelc.apollopre.module.web.WebPageActivity;
import com.bulletelc.apollopre.utils.RegExUtil;
import com.bulletelc.apollopre.utils.ToastUtil;

/**
 * Created by CX on 2018/4/11.
 */

public class FastRegisterFragment extends MVPBaseFragment<FastContract.View, FastPresenter> implements FastContract.View,
        View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    // views
    private EditText etPhone;
    private EditText etPassword;
    private EditText etAuthCode;
    private Button btnAuthCode;
    private Button btnRegister;
    private TextView tvRegisterAgreement;
    private CheckBox cbAgreement;

    // data
    private String authCode;
    private String encrypt;
    private String rePhone; //防止手机被篡改

    public static FastRegisterFragment getInstance() {
        FastRegisterFragment fragment = new FastRegisterFragment();
        return fragment;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnAuthCode:
                sendSMS();
                break;
            case R.id.btnRegister:
                register();
                break;
            case R.id.tvRegisterAgreement:
                registerAgreement();
                break;
            default:
                break;
        }
    }

    @Override
    public int getLayoutRes() {
        return R.layout.fast_register_fragment;
    }

    @Override
    public void assignViews() {
        etPhone = findView(R.id.etPhone);
        etPassword = findView(R.id.etPassword);
        etAuthCode = findView(R.id.etAuthCode);
        btnAuthCode = findView(R.id.btnAuthCode);
        btnRegister = findView(R.id.btnRegister);
        tvRegisterAgreement = findView(R.id.tvRegisterAgreement);
        cbAgreement = findView(R.id.cbAgreement);
    }

    @Override
    public void setListener() {
        btnAuthCode.setOnClickListener(this);
        btnRegister.setOnClickListener(this);
        tvRegisterAgreement.setOnClickListener(this);
        cbAgreement.setOnCheckedChangeListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        tvRegisterAgreement.setText("<<用户注册协议>>");
    }

    @Override
    public void onSuccessSMS(String authCode, String encrypt) {
        this.authCode = authCode;
        this.encrypt = encrypt;
        Toast.makeText(getActivity(), getString(R.string.toast_send_sms_success), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFailSMS(String fail) {
        Toast.makeText(getActivity(), fail, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onErrorSMS(String error) {
        Toast.makeText(getActivity(), error, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onSuccess() {
        presenter.autoLogin(rePhone, etPassword.getText().toString());
    }

    @Override
    public void onFail(String fail) {
        btnRegister.setEnabled(true);
        Toast.makeText(getActivity(), fail, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onError(String error) {
        btnRegister.setEnabled(true);
        ToastUtil.showLongToast(getActivity(), R.string.network_msg);
    }

    @Override
    public void onSuccessAutoLogin() {
        presenter.getSetting();
    }

    @Override
    public void onErrorAutoLogin(String error) {
        ToastUtil.showLongToast(getActivity(), R.string.network_msg);
    }

    @Override
    public void onFailAutoLogin(String fail) {
        ToastUtil.showLongToast(getActivity(), fail);
    }

    @Override
    public void onSuccessGetSetting() {
        Intent intent = new Intent(getActivity(), MainActivity.class);
        intent.putExtra(IntentCode.EXTRA_KEY_FRAGMENT_POSITION, 3);
        getActivity().startActivity(intent);
        getActivity().finish();
    }

    @Override
    public void onFailGetSetting(String fail) {
        ToastUtil.showLongToast(getContext(), fail);
    }

    @Override
    public void onErrorGetSetting(String error) {
        ToastUtil.showLongToast(getContext(), error);
    }

    @Override
    protected FastPresenter createPresenter() {
        return new FastPresenter();
    }

    private void sendSMS() {
        String phone = etPhone.getText().toString().trim();
        if (!RegExUtil.isMobileExact(phone)) {
            etPhone.setError(getString(R.string.hint_input_correct_mobile));
            return;
        }
        rePhone = phone;
        presenter.sendSMS(phone);
        btnAuthCode.setEnabled(false);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 60; i >= 0; i--) {
                    final int finalI = i;
                    btnAuthCode.post(new Runnable() {
                        @Override
                        public void run() {
                            btnAuthCode.setText(finalI + "s");
                        }
                    });
                    if (i == 0) {
                        btnAuthCode.post(new Runnable() {
                            @Override
                            public void run() {
                                btnAuthCode.setEnabled(true);
                                btnAuthCode.setText(R.string.btn_send_again);
                            }
                        });
                    }
                    try {
                        Thread.sleep(999);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

            }
        }).start();
    }

    /**
     * 注册
     */
    private void register() {
        String phone = etPhone.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String authCode = etAuthCode.getText().toString().trim();
        String unionid = ((LoginMainActivity) getActivity()).getUnionid();

        if (!RegExUtil.isMobileExact(phone)) {
            etPhone.setError(getString(R.string.hint_input_correct_mobile));
            return;
        }

        if (password == null || password.length() < 6) {
            etPassword.setError(getString(R.string.hint_input_six_password));
            return;
        }

        //验证 验证码
        if (authCode == null || !authCode.equals(this.authCode)) {
            Toast.makeText(getActivity(), getString(R.string.hint_input_correct_auth_code), Toast.LENGTH_SHORT).show();
            return;
        }

        if (!rePhone.equals(phone)) {
            ToastUtil.showShortToast(getActivity(), "手机号已被更改，请重新发送短信验证码");
            return;
        }

        btnRegister.setEnabled(false);//禁用，防止抖动
        presenter.register(phone, password, encrypt, unionid);
    }

    private void registerAgreement() {
        Intent intent = new Intent(getActivity(), WebPageActivity.class);
        intent.putExtra(IntentCode.EXTRA_KEY_URL, NetWorkPath.GET_REGISTER_AGREEMENT);
        intent.putExtra(IntentCode.EXTRA_WEB_PAGE_FLAG, GlobalConfig.WEB_PAGE_FOR_AGREEMENT);
        startActivity(intent);
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if (b) {
            btnRegister.setEnabled(true);
        } else {
            btnRegister.setEnabled(false);
        }
    }
}
